﻿namespace CloudBlitz.DeploymentManager
{
    using System;
    using System.IO;
    using System.Net;

    using CloudBlitz.DeploymentManager.DeploymentWorkflow;

    public static class ExceptionHelper
    {
        public static OperationResult HandleException(Exception exception)
         {
             if (exception is AggregateException)
             {
                 if (exception.InnerException is WebException)
                 {
                     var webException = exception.InnerException as WebException;
                     var operationId = webException.Response.Headers["x-ms-request-id"];
                     if (webException.Response != null)
                     {
                         using (var streamReader = new StreamReader(webException.Response.GetResponseStream()))
                         {
                             return CreateResult(string.Format("Exception: {0}, Response: {1}, OperationId: {2}", exception.ToString(), streamReader.ReadToEnd(), operationId));
                         }
                     }

                     return CreateResult(string.Format("Exception: {0}, OperationId: {1}", exception.ToString(), operationId));
                 }

                 return CreateResult(exception.InnerException.ToString());
             }

             return CreateResult(exception.ToString());
         }

        private static OperationResult CreateResult(string message)
        {
            return new OperationResult(DeploymentOperationStatus.Failed, message);
        }
    }
}